package dxn.nl.file.api;

import dxn.nl.file.biz.manager.MinIoImageManager;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

@Slf4j
@RestController
@RequestMapping("/file/download")
@Tag(name = "文件下载")
public class FileDownLoadControl {

    @Resource
    private MinIoImageManager minIoImageManager;

    private String defaultBucketName= "cms";

    @Operation(summary = "通过路径导出文件")
    @RequestMapping(value = "/byFilePath",method = {RequestMethod.POST,RequestMethod.GET})
    public ResponseEntity byFilePath(@RequestParam(name = "fileName") String fileName) throws Exception{
        String sysCode = "cms";
        if(fileName.startsWith("/"))
        {
            fileName = fileName.substring(1);
        }

        int lastFileSplit = fileName.indexOf("/");
        if(lastFileSplit>0)
        {
            String path = fileName.substring(0,lastFileSplit);

            if(minIoImageManager.existBucketName(path))
            {
                sysCode = path;
            }

            fileName = fileName.substring(lastFileSplit+1);
        }
        if(StringUtils.isBlank(sysCode))
        {
            sysCode = defaultBucketName;
        }

        InputStream stream = minIoImageManager.getImage(sysCode,fileName);
        return dealResult(stream,fileName);
    }

    private ResponseEntity dealResult(InputStream stream, String path) throws Exception
    {
        String fileName = "";
        int lastFileSplit = path.lastIndexOf("/");
        if(lastFileSplit>0)
        {
            fileName = path.substring(lastFileSplit+1);
        }

        // 解析文件的 mime 类型
        String mediaTypeStr = URLConnection.getFileNameMap().getContentTypeFor(fileName);
        if(StringUtils.isBlank(mediaTypeStr))
        {
            // 无法判断MIME类型时，作为流类型
            mediaTypeStr = (mediaTypeStr == null) ? MediaType.APPLICATION_OCTET_STREAM_VALUE : mediaTypeStr;
        }

        // 实例化MIME
        MediaType mediaType = MediaType.parseMediaType(mediaTypeStr);


        /*
         * 构造响应的头
         */
        HttpHeaders headers = new HttpHeaders();
        // 下载之后需要在请求头中放置文件名，该文件名按照ISO_8859_1编码。
        String filenames = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        headers.setContentDispositionFormData("attachment", filenames);
        headers.setContentType(mediaType);

        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        int ch;
        while ((ch = stream.read()) != -1) {
            swapStream.write(ch);
        }

        /*
         * 返还资源
         */
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(swapStream.size())
                .body(swapStream.toByteArray());
    }
}
